# Create your views here.
from django.core.cache import cache
from rest_framework.mixins import CreateModelMixin
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import GenericViewSet, ViewSet
from rest_framework_jwt.authentication import JSONWebTokenAuthentication

from lib.iPay import alipay
from utils.logging import get_logger
from utils.response import APIResponse
from vip.models import VipCard
from vip.serializer import VipcardSerializer
from . import models
from .models import Order
# 登录才能使用，认证类:自己写一个认证类  使用jwt内置的认证类，配合一个权限类
from .serializers import PaySerializer, PayCourseSerializer, VipcardOrderSerializer, CourseOrderSerializer

logger = get_logger()


class PayViewSet(GenericViewSet, CreateModelMixin):
    authentication_classes = [JSONWebTokenAuthentication, ]
    permission_classes = [IsAuthenticated]
    queryset = Order.objects.all()
    serializer_class = PaySerializer

    def create(self, request, *args, **kwargs):
        token = request.META.get("HTTP_AUTHORIZATION")
        subject = request.data.get('subject')
        t_s = str(token + subject)
        token_subject = cache.get(t_s)
        if token_subject:
            return APIResponse(code=101, msg='重复操作')
        else:
            cache.set(t_s, 1, 30)
        serializer = self.get_serializer(data=request.data, context={'request': request})
        serializer.is_valid(raise_exception=True)  # 字段自己的校验，局部钩子，全局钩子
        self.perform_create(serializer)
        pay_url = serializer.context['pay_url']
        return APIResponse(pay_url=pay_url)


class AliPayView(APIView):
    def post(self, request):
        try:
            result_data = request.data.dict()
            out_trade_no = result_data.get('out_trade_no')
            signature = result_data.pop('sign')
            result = alipay.verify(result_data, signature)
            if result and result_data["trade_status"] in ("TRADE_SUCCESS", "TRADE_FINISHED"):
                models.Order.objects.filter(out_trade_no=out_trade_no).update(order_status=1)
                logger.warning('%s订单支付成功' % out_trade_no)
                return Response('success')
            else:
                logger.error('%s订单支付失败' % out_trade_no)
        except:
            pass
        return Response('failed')

    def get(self, request):
        print('来了')
        out_trade_no = request.query_params.get('out_trade_no')
        try:
            models.Order.objects.get(out_trade_no=out_trade_no, order_status=1)
            # models.Order.objects.filter(out_trade_no=out_trade_no).update(order_status=1)
            return APIResponse(result=True)
        except:
            return APIResponse(code=101, msg='error', result=False)


class PayCourseViewSet(GenericViewSet, CreateModelMixin):
    authentication_classes = [JSONWebTokenAuthentication, ]
    permission_classes = [IsAuthenticated]
    queryset = Order.objects.all()
    serializer_class = PayCourseSerializer

    def create(self, request, *args, **kwargs):
        token = request.META.get("HTTP_AUTHORIZATION")
        subject = request.data.get('subject')
        t_s = str(token + subject)
        token_subject = cache.get(t_s)
        if token_subject:
            return APIResponse(code=101, msg='重复操作')
        else:
            cache.set(t_s, 1, 30)
        serializer = self.get_serializer(data=request.data, context={'request': request})
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        pay_url = serializer.context['pay_url']
        return APIResponse(pay_url=pay_url)


class AliPayCourseView(APIView):
    def post(self, request):
        try:
            result_data = request.data.dict()
            out_trade_no = result_data.get('out_trade_no')
            signature = result_data.pop('sign')
            result = alipay.verify(result_data, signature)
            if result and result_data["trade_status"] in ("TRADE_SUCCESS", "TRADE_FINISHED"):
                models.CourseOrder.objects.filter(out_trade_no=out_trade_no).update(order_status=1)
                logger.warning('%s订单支付成功' % out_trade_no)
                return Response('success')
            else:
                logger.error('%s订单支付失败' % out_trade_no)
        except:
            pass
        return Response('failed')

    def get(self, request):
        print('来了')
        out_trade_no = request.query_params.get('out_trade_no')
        try:
            # models.CourseOrder.objects.get(out_trade_no=out_trade_no, order_status=1)
            models.CourseOrder.objects.filter(out_trade_no=out_trade_no).update(order_status=1)
            return APIResponse(result=True)
        except:
            return APIResponse(code=101, msg='error', result=False)


class VipcardOrderViewSet(ViewSet):
    def post(self, request):
        res = models.Order.objects.filter(user=request.data['user']).all()
        ser = VipcardOrderSerializer(instance=res, many=True)
        return APIResponse(msg=ser.data)


class CourseOrderViewSet(ViewSet):
    def post(self, request):
        res = models.CourseOrder.objects.filter(user=request.data['user']).all()
        ser = CourseOrderSerializer(instance=res, many=True)
        return APIResponse(msg=ser.data)


class VipNumView(ViewSet):
    def list(self, request):
        res = Order.objects.filter(out_trade_no=request.data['out_trade_no']).first()
        ser = VipcardOrderSerializer(instance=res)
        res2 = VipCard.objects.filter(cardname=ser.data['subject']).first()
        ser2 = VipcardSerializer(instance=res2)
        return APIResponse(msg=ser2.data)
